<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <!--设备数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="mac地址" prop="mac" label-width="24">
            <el-input
              v-model="queryParams.mac"
              placeholder="请输入mac地址"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="产品类型">
            <el-select v-model="queryParams.pId">
              <el-option
                v-for="item in productOptions"
                :key="item.pId"
                :label="item.pClass"
                :value="item.pId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="采样率" prop="samplerate">
            <el-input
              v-model="queryParams.samplerate"
              placeholder="请输入采样率"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="设备状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['equipment:equipment:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['equipment:equipment:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['equipment:equipment:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['equipment:equipment:export']"
            >导出</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="设备id" align="center" prop="id" />
            <el-table-column label="产品类型" align="center" prop="product.pClass" />
            <el-table-column label="使用者" align="center">
              <template slot-scope="scope">
                <el-select v-model = "scope.row.users.nickName" placeholder="查看用户">
                  <el-option
                    v-for="item in scope.row.users"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                    :disabled="item.status ==1 "
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="部门" align="center" prop="dept.deptName" :show-overflow-tooltip="true" />
            <el-table-column label="磁盘总容量" align="center" prop="disktotalcapacity" />
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['equipment:equipment:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['equipment:equipment:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="mac地址" prop="mac">
        <el-input v-model="form.mac" placeholder="请输入mac地址" />
      </el-form-item>

      <el-form-item label="产品类型" prop="pId">
        <el-select v-model="form.pId" placeholder="请选择">
          <el-option
            v-for="item in productOptions"
            :key="item.pId"
            :label="item.pClass"
            :value="item.pId"
            :disabled="item.status == 1"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="归属部门" prop="deptId">
        <treeselect v-model="form.deptId" :options="deptOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择归属部门" />
      </el-form-item>

      <el-form-item label="用户">
        <el-select v-model="form.userIds" multiple placeholder="请选择">
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
            :disabled="item.status == 1"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="磁盘总容量" prop="disktotalcapacity">
        <el-input v-model="form.disktotalcapacity" placeholder="请输入磁盘总容量" />
      </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment, exportEquipment } from "@/api/equipment/equipment";
  import {changeEquipmentStatus} from "../../../api/equipment/equipment";

  export default {
    name: "Equipment",
    components: { Treeselect },
    data() {
      return {
        // 部门名称
        deptName: undefined,
        // 部门树选项
        deptOptions: undefined,
        // 产品名称
        productName: undefined,
        // 产品类型选项
        productOptions: undefined,
        // 设备状态字典
        statusOptions: [],
        // 用户选项
        userOptions: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 设备信息表格数据
        equipmentList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          mac: undefined,
          pId: undefined,
          deptId: undefined,
          disktotalcapacity: undefined,
          batpt: undefined,
          disksurpluscapacity: undefined,
          hasfile: undefined,
          samplerate: undefined,
          netdelay: undefined,
          status: undefined
        },
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          mac: [
            { required: true, message: "mac地址不能为空", trigger: "blur" }
          ],
          pId: [
            { required: true, message: "产品id不能为空", trigger: "blur" }
          ],
          deptId: [
            { required: true, message: "设备所属部门ID不能为空", trigger: "blur" }
          ],
          disktotalcapacity: [
            { required: true, message: "磁盘总容量不能为空", trigger: "blur" }
          ],
        }
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.getList();
      this.getTreeselect();

      // this.queryParams.deptId = this.deptOptions.id;

      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      getEquipment().then(
        response => {
          this.productOptions = response.product;
        }
      );
    },

    methods: {
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      /** 查询设备信息列表 */
      getList() {
        this.loading = true;
        listEquipment(this.queryParams).then(response => {
          this.equipmentList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id;
        this.getList();
      },
      // 设备状态修改
      handleStatusChange(row) {
        // 可以看到scope.row的参数,其中有user选项
        console.log(row)
        let text = row.status === "0" ? "启用" : "停用";

        this.$confirm('确认要' + text + '设备'+row.id+'吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeEquipmentStatus(row.id, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 表单重置
      reset() {
        this.form = {
          //这里的id就是equipmentId，这里不知道为什么可以这样
          id: undefined,
          mac: undefined,
          pId: undefined,
          deptId: undefined,
          disktotalcapacity: undefined,
          batpt: undefined,
          disksurpluscapacity: undefined,
          hasfile: undefined,
          samplerate: undefined,
          netdelay: undefined,
          status: undefined,
          userIds: []
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getTreeselect();
        this.open = true;
        this.title = "新增设备";
        getEquipment().then(response => {
          this.userOptions = response.user;
          this.productOptions = response.product;
          console.log(response.product);
        });

      },
      /** 修改按钮操作 */
      handleUpdate: function (row) {
        this.reset();
        this.getTreeselect();
        const id = row.id || this.ids
        getEquipment(id).then(response => {
          this.productOptions = response.product;
          this.form = response.data;
          //这里用users好像有unresolved
          this.userOptions = response.user;
          this.userIds = response.userIds;
          this.open = true;
          this.title = "修改设备信息";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {

              updateEquipment(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addEquipment(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除设备信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delEquipment(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有设备信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportEquipment(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
